

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="John Doe">
  <meta name="keywords" content="">
  
    <meta name="description" content="@[TOC] 一、Runtime 饿汉式 java.lang.Runtime 是从 JDK1.0 就开始出现的类，每个Java应用程序都有一个 Runtime 实例，该实例允许应用程序与运行应用程序的环境交互。当前运行时可以从getRuntime方法获得。 【例1】使用 Runtime 对象打开系统的记事本 123456public class Demo&amp;#123;    public stati">
<meta property="og:type" content="article">
<meta property="og:title" content="设计模式 笔记3 _ 单例模式 在源码中的应用 Runtime 、Integer、Spring @Bean">
<meta property="og:url" content="http://example.com/2022/07/29/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%20%E7%AC%94%E8%AE%B03%20_%20%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F%20%E5%9C%A8%E6%BA%90%E7%A0%81%E4%B8%AD%E7%9A%84%E5%BA%94%E7%94%A8%20Runtime%20%E3%80%81Integer%E3%80%81Spring%20@Bean/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="@[TOC] 一、Runtime 饿汉式 java.lang.Runtime 是从 JDK1.0 就开始出现的类，每个Java应用程序都有一个 Runtime 实例，该实例允许应用程序与运行应用程序的环境交互。当前运行时可以从getRuntime方法获得。 【例1】使用 Runtime 对象打开系统的记事本 123456public class Demo&amp;#123;    public stati">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://img-blog.csdnimg.cn/5adfe52c176446ecb7173d071c5fd283.gif#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/2614d9ab2f1a441bae314b9aafdd63b4.gif#pic_center">
<meta property="article:published_time" content="2022-07-29T09:03:04.000Z">
<meta property="article:modified_time" content="2022-08-22T15:41:21.041Z">
<meta property="article:author" content="John Doe">
<meta property="article:tag" content="设计模式">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/5adfe52c176446ecb7173d071c5fd283.gif#pic_center">
  
  
  
  <title>设计模式 笔记3 _ 单例模式 在源码中的应用 Runtime 、Integer、Spring @Bean - Hexo</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.2","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.2.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>尤 Ni&#39;s Blog</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="设计模式 笔记3 _ 单例模式 在源码中的应用 Runtime 、Integer、Spring @Bean"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        John Doe
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-07-29 17:03" pubdate>
          2022年7月29日 下午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          9.9k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          83 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">设计模式 笔记3 _ 单例模式 在源码中的应用 Runtime 、Integer、Spring @Bean</h1>
            
              <p class="note note-info">
                
                  
                    本文最后更新于：1 小时前
                  
                
              </p>
            
            
              <div class="markdown-body">
                
                <p>@[TOC]</p>
<h1 id="一、Runtime-饿汉式"><a href="#一、Runtime-饿汉式" class="headerlink" title="一、Runtime 饿汉式"></a>一、Runtime 饿汉式</h1><hr>
<p><code>java.lang.Runtime</code> 是从 JDK1.0 就开始出现的类，每个Java应用程序都有一个 Runtime 实例，该实例允许应用程序与运行应用程序的环境交互。当前运行时可以从getRuntime方法获得。</p>
<p>【例1】使用 Runtime 对象打开系统的记事本</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">Demo</span>&#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> <span class="hljs-keyword">throws</span> IOException &#123;<br>        <span class="hljs-type">Runtime</span> <span class="hljs-variable">runtime</span> <span class="hljs-operator">=</span> Runtime.getRuntime();<br>        runtime.exec(<span class="hljs-string">&quot;notepad&quot;</span>);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<p>【例2】使用 Runtime 对象打开系统的计算器</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-type">Runtime</span> <span class="hljs-variable">runtime</span> <span class="hljs-operator">=</span> Runtime.getRuntime();<br>runtime.exec(<span class="hljs-string">&quot;calc&quot;</span>);<br></code></pre></td></tr></table></figure>
<p>【例3】使用 Runtime 对象实现10秒后自动关机</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-type">Runtime</span> <span class="hljs-variable">runtime</span> <span class="hljs-operator">=</span> Runtime.getRuntime();<br>runtime.exec(<span class="hljs-string">&quot;shutdown -s -t 10&quot;</span>);<br></code></pre></td></tr></table></figure>

<p>这个类内部用到了单例模式中的饿汉式</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">Runtime</span> &#123;<br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-type">Runtime</span> <span class="hljs-variable">currentRuntime</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Runtime</span>();<br><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Runtime <span class="hljs-title function_">getRuntime</span><span class="hljs-params">()</span> &#123;<br>        <span class="hljs-keyword">return</span> currentRuntime;<br>    &#125;<br>    <br>    <span class="hljs-keyword">private</span> <span class="hljs-title function_">Runtime</span><span class="hljs-params">()</span> &#123;&#125;<br>    ...<br>&#125;<br></code></pre></td></tr></table></figure>

<h1 id="二、Integer-封装类型中的单例"><a href="#二、Integer-封装类型中的单例" class="headerlink" title="二、Integer 封装类型中的单例"></a>二、Integer 封装类型中的单例</h1><hr>
<h2 id="2-1-自动装箱与自动拆箱"><a href="#2-1-自动装箱与自动拆箱" class="headerlink" title="2.1 自动装箱与自动拆箱"></a>2.1 自动装箱与自动拆箱</h2><p>JDK8中的 Integer 是 int 类型的封装类型，可以直接互相转换，这个过程称为自动装箱和自动拆箱</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">Demo</span>&#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> &#123;<br>        <span class="hljs-type">Integer</span> <span class="hljs-variable">a</span> <span class="hljs-operator">=</span> <span class="hljs-number">10</span>;<br>        <span class="hljs-type">int</span> <span class="hljs-variable">b</span> <span class="hljs-operator">=</span> a;<br>        System.out.println(a +<span class="hljs-string">&quot;=&quot;</span> + b);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>那么它是如何实现 Integer -&gt; int 自动拆箱类型的转换的呢？其实不用去硬记，我们直接调试一下就知道了，这里我使用的是 IDEA 工具<br><img src="https://img-blog.csdnimg.cn/5adfe52c176446ecb7173d071c5fd283.gif#pic_center" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p>通过调试可以看出， int -&gt; Integer 本质上是调用了 Integer类中的 静态方法 valueOf()，而且这里我们返回的是 IntegerCache.cache里缓存的值</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Integer <span class="hljs-title function_">valueOf</span><span class="hljs-params">(<span class="hljs-type">int</span> i)</span> &#123;<br>    <span class="hljs-keyword">if</span> (i &gt;= IntegerCache.low &amp;&amp; i &lt;= IntegerCache.high)<br>        <span class="hljs-keyword">return</span> IntegerCache.cache[i + (-IntegerCache.low)];<br>    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Integer</span>(i);<br>&#125;<br></code></pre></td></tr></table></figure>
<p>而 Integer -&gt; int 本质上则调用了 Integer 类中的对象方法 intValue </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-type">int</span> <span class="hljs-title function_">intValue</span><span class="hljs-params">()</span> &#123;<br>    <span class="hljs-keyword">return</span> value;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>通过上面这个小例子，我们引入了 Integer类中的单例应用，静态内部类 IntegerCache，这个类是用来缓存 [-128 ~ 127] 的整型变量的，假如我们定义的a是大于127的数，比如128，调试看看结果：</p>
<p><img src="https://img-blog.csdnimg.cn/2614d9ab2f1a441bae314b9aafdd63b4.gif#pic_center" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p>在 valueOf() 方法中判断整型变量的值超出了缓存的范围，于是就直接返回一个新的 Integer对象。</p>
<h2 id="2-2-IntegerCache-饿汉式"><a href="#2-2-IntegerCache-饿汉式" class="headerlink" title="2.2 IntegerCache 饿汉式"></a>2.2 IntegerCache 饿汉式</h2><h3 id="2-2-1-拓展-Java类加载机制"><a href="#2-2-1-拓展-Java类加载机制" class="headerlink" title="2.2.1 拓展: Java类加载机制"></a>2.2.1 拓展: Java类加载机制</h3><p><code>Integer.IntegerCache</code> 的源码如下，根据之前的学习我们可以判定这就是一个单例模式的具体实现，因为它具有以下几个特点，类是静态的，且构造方法私有化   private IntegerCache() {}，除此之外，其内部变量以及一些初始化均是 static 修饰的，毕竟它的作用就是缓存，得在执行前就初始化完毕。<br>根据 Java 的类加载机制，对于静态类来说，访问到其内部的静态方法或非final修饰的静态变量或对象变量、对象方法，其内部的静态代码块才会执行，例如：我们只访问静态类中final修饰的静态成员变量 a</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">Demo</span>&#123;<br>    <span class="hljs-keyword">static</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">Test</span>&#123;<br>        <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">static</span> <span class="hljs-type">int</span> <span class="hljs-variable">a</span> <span class="hljs-operator">=</span> <span class="hljs-number">0</span>;<br>        <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">hello</span><span class="hljs-params">()</span>&#123;<br>            System.out.println(<span class="hljs-string">&quot;World!&quot;</span>);<br>        &#125;<br>        <span class="hljs-keyword">static</span>&#123;<br>            System.out.print(<span class="hljs-string">&quot;Hello,&quot;</span>);<br>        &#125;<br>    &#125;<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> &#123;<br>        System.out.println(Test.a);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
<blockquote>
<p>运行结果：0</p>
</blockquote>
<p>static { } 里的内容并没有执行，但是当我们直接调用hello方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> &#123;<br>    Test.hello();<br>&#125;<br></code></pre></td></tr></table></figure>

<blockquote>
<p>运行结果：Hello, World! </p>
</blockquote>
<p>static{ } 里的内容执行了，而且是在调用的静态方法前执行的<br>Integer 里的IntergerCache 里只有 static final 变量，那么它的 static 执行过程应该是在程序启动的时候就执行了，否则这里面对 static final 变量的修改是不合法的。</p>
<h3 id="2-2-2-单例模式的源码浅析"><a href="#2-2-2-单例模式的源码浅析" class="headerlink" title="2.2.2 单例模式的源码浅析"></a>2.2.2 单例模式的源码浅析</h3><p>通过源码我们发现， Integer 缓存的最高值是可以调整的，通过  java.lang.Integer.IntegerCache.high 参数</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">IntegerCache</span> &#123;<br>     <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">int</span> <span class="hljs-variable">low</span> <span class="hljs-operator">=</span> -<span class="hljs-number">128</span>;<br>     <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">int</span> high;<br>     <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> Integer cache[];<br><br>     <span class="hljs-keyword">static</span> &#123;<br>         <span class="hljs-comment">// 设置缓存的最高值</span><br>         <span class="hljs-type">int</span> <span class="hljs-variable">h</span> <span class="hljs-operator">=</span> <span class="hljs-number">127</span>;<br>         <span class="hljs-type">String</span> <span class="hljs-variable">integerCacheHighPropValue</span> <span class="hljs-operator">=</span><br>             sun.misc.VM.getSavedProperty(<span class="hljs-string">&quot;java.lang.Integer.IntegerCache.high&quot;</span>);<br>         <span class="hljs-comment">// 如果Integer缓存的配置不为空，则尝试修改缓存的最高值</span><br>         <span class="hljs-keyword">if</span> (integerCacheHighPropValue != <span class="hljs-literal">null</span>) &#123;<br>             <span class="hljs-keyword">try</span> &#123;<br>                 <span class="hljs-type">int</span> <span class="hljs-variable">i</span> <span class="hljs-operator">=</span> parseInt(integerCacheHighPropValue);<br>                 i = Math.max(i, <span class="hljs-number">127</span>);<br>                 <span class="hljs-comment">// 缓存最大限制Integer的最大值</span><br>                 h = Math.min(i, Integer.MAX_VALUE - (-low) -<span class="hljs-number">1</span>);<br>             &#125; <span class="hljs-keyword">catch</span>( NumberFormatException nfe) &#123;<br>                 <span class="hljs-comment">// 如果传的参数无法转为 int，则忽略</span><br>             &#125;<br>         &#125;<br>         high = h;<br>         <span class="hljs-comment">// 定义缓存数组</span><br>         cache = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Integer</span>[(high - low) + <span class="hljs-number">1</span>];<br>         <span class="hljs-type">int</span> <span class="hljs-variable">j</span> <span class="hljs-operator">=</span> low;<br>         <span class="hljs-comment">// 逐一创建 Integer 对象</span><br>         <span class="hljs-keyword">for</span>(<span class="hljs-type">int</span> <span class="hljs-variable">k</span> <span class="hljs-operator">=</span> <span class="hljs-number">0</span>; k &lt; cache.length; k++)<br>             cache[k] = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Integer</span>(j++);<br><br>         <span class="hljs-comment">// 缓存最高值必须大于或等于 127</span><br>         <span class="hljs-keyword">assert</span> IntegerCache.high &gt;= <span class="hljs-number">127</span>;<br>     &#125;<br>     <span class="hljs-comment">// 构造方法私有化</span><br>     <span class="hljs-keyword">private</span> <span class="hljs-title function_">IntegerCache</span><span class="hljs-params">()</span> &#123;&#125;<br> &#125;<br></code></pre></td></tr></table></figure>
<h1 id="三、Spring-源码中的单例"><a href="#三、Spring-源码中的单例" class="headerlink" title="三、Spring 源码中的单例"></a>三、Spring 源码中的单例</h1><blockquote>
<p>Spring 版本：v5.3.21</p>
</blockquote>
<p>在Spring中，bean可以被定义为两种模式，prototype（多例）和 singleton（单例）</p>
<ul>
<li>singleton（单例），只有一个共享的实例存在，所有对这个bean的请求都会返回唯一的实例。</li>
<li>prototype（多例），对这个bean的每次请求都会创建一个新的bean实例，类似于 new</li>
</ul>
<p>现在基本上都是 SpringBoot 开发，于是我们直接用 SpringBoot 来测试<br>【例1】SpringBoot 里往 IOC 容器注册单例模式的 Bean</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@SpringBootApplication</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">WebDemoApplication</span> &#123;<br>    <span class="hljs-meta">@Bean</span><br>    <span class="hljs-meta">@Scope(&quot;singleton&quot;)</span><br>    <span class="hljs-keyword">public</span> String <span class="hljs-title function_">uuid</span><span class="hljs-params">()</span>&#123;<br>        <span class="hljs-keyword">return</span> UUID.randomUUID().toString();<br>    &#125;<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> &#123;<br>        <span class="hljs-type">ApplicationContext</span> <span class="hljs-variable">context</span> <span class="hljs-operator">=</span> SpringApplication.run(WebDemoApplication.class, args);<br>        <span class="hljs-type">String</span> <span class="hljs-variable">id1</span> <span class="hljs-operator">=</span> context.getBean(String.class);<br>        <span class="hljs-type">String</span> <span class="hljs-variable">id2</span> <span class="hljs-operator">=</span> context.getBean(String.class);<br>        System.out.println(<span class="hljs-string">&quot;id1:&quot;</span> + id1);<br>        System.out.println(<span class="hljs-string">&quot;id2:&quot;</span> + id2);<br>    &#125;<br>&#125;<br><span class="hljs-comment">// 运行结果: 输出了相同的id</span><br><span class="hljs-comment">// id1:8b58cfd1-ba2c-4759-96d9-fbc44f8a66b5</span><br><span class="hljs-comment">// id2:8b58cfd1-ba2c-4759-96d9-fbc44f8a66b5</span><br></code></pre></td></tr></table></figure>
<p>【例2】SpringBoot 里往 IOC 容器注册多例模式的 Bean</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Bean</span><br><span class="hljs-meta">@Scope(&quot;prototype&quot;)</span><br><span class="hljs-keyword">public</span> String <span class="hljs-title function_">uuid</span><span class="hljs-params">()</span>&#123;<br>    <span class="hljs-keyword">return</span> UUID.randomUUID().toString();<br>&#125;<br></code></pre></td></tr></table></figure>
<p>Spring 注入 Bean时候默认是单例模式</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Bean</span><br><span class="hljs-meta">@Scope</span><br><span class="hljs-keyword">public</span> String <span class="hljs-title function_">uuid</span><span class="hljs-params">()</span>&#123;<br>    <span class="hljs-keyword">return</span> UUID.randomUUID().toString();<br>&#125;<br></code></pre></td></tr></table></figure>
<p>Spring 中加载单例的过程是在 BeanFactory 接口里的 getBean()方法中被定义，例如之前例子中的getBean()其源码实现为：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs java">&lt;T&gt; T <span class="hljs-title function_">getBean</span><span class="hljs-params">(Class&lt;T&gt; requiredType)</span> <span class="hljs-keyword">throws</span> BeansException;<br></code></pre></td></tr></table></figure>
<p>通过调试，在执行这个方法时候，跳转到的实现类为：<code>AbstractApplicationContext.java</code></p>
<ol>
<li>首先检查 Bean工厂是否启用</li>
<li>然后在获取Bean 工厂，从而获取Bean</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Override</span><br><span class="hljs-keyword">public</span> &lt;T&gt; T <span class="hljs-title function_">getBean</span><span class="hljs-params">(Class&lt;T&gt; requiredType)</span> <span class="hljs-keyword">throws</span> BeansException &#123;<br>    assertBeanFactoryActive();<br>    <span class="hljs-keyword">return</span> getBeanFactory().getBean(requiredType);<br>&#125;<br></code></pre></td></tr></table></figure>
<p>获取 Bean 用到了 <code>DefaultListableBeanFactory</code> 工厂类</p>
<ol>
<li><p>判断获取Bean类型不为空</p>
</li>
<li><p>调用 resolveBean 方法解析 Bean</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> &lt;T&gt; T <span class="hljs-title function_">getBean</span><span class="hljs-params">(Class&lt;T&gt; requiredType, <span class="hljs-meta">@Nullable</span> Object... args)</span> <br>    <span class="hljs-keyword">throws</span> BeansException &#123;<br>    Assert.notNull(requiredType, <span class="hljs-string">&quot;Required type must not be null&quot;</span>);<br>    <span class="hljs-type">Object</span> <span class="hljs-variable">resolved</span> <span class="hljs-operator">=</span> resolveBean(ResolvableType.forRawClass(requiredType), args, <span class="hljs-literal">false</span>);<br>    <span class="hljs-keyword">if</span> (resolved == <span class="hljs-literal">null</span>) &#123;<br>      <span class="hljs-comment">// throw ... 抛出找不到Bean的异常</span><br>    &#125;<br>    <span class="hljs-keyword">return</span> (T) resolved;<br>&#125;<br></code></pre></td></tr></table></figure>
<p>resolveBean () 方法的关键如下：</p>
</li>
<li><p>调用 resolveNamedBean() 方法，获取当前类型的名称Bean，不为空则直接返回实例化对象</p>
</li>
<li><p>获取Bean工厂，使用工厂来解析Bean，或通过工厂的Bean提供者来返回对象</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs java">NamedBeanHolder&lt;T&gt; namedBean = resolveNamedBean(requiredType, args, nonUniqueAsNull)<br>    <br><span class="hljs-type">BeanFactory</span> <span class="hljs-variable">parent</span> <span class="hljs-operator">=</span> getParentBeanFactory();<br></code></pre></td></tr></table></figure>
<p>resolveNamedBean() 方法的关键如下：</p>
</li>
<li><p>获取 Bean对应的名称</p>
</li>
<li><p>如果 class字节码对应的Bean只有一个，那么直接调用 resolveNamedBean() 方法返回</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java">String[] candidateNames = getBeanNamesForType(requiredType);<br><br><span class="hljs-keyword">if</span> (candidateNames.length == <span class="hljs-number">1</span>) &#123;<br>    <span class="hljs-keyword">return</span> resolveNamedBean(candidateNames[<span class="hljs-number">0</span>], requiredType, args);<br>&#125;<br></code></pre></td></tr></table></figure>
<p>resolveNamedBean()重载方法关键如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">private</span> &lt;T&gt; NamedBeanHolder&lt;T&gt; <span class="hljs-title function_">resolveNamedBean</span><span class="hljs-params">(</span><br><span class="hljs-params">    String beanName, ResolvableType requiredType, <span class="hljs-meta">@Nullable</span> Object[] args)</span> <span class="hljs-keyword">throws</span> BeansException &#123;<br>    <span class="hljs-comment">// 调用重载方法 getBean</span><br>    <span class="hljs-type">Object</span> <span class="hljs-variable">bean</span> <span class="hljs-operator">=</span> getBean(beanName, <span class="hljs-literal">null</span>, args);<br>    <span class="hljs-comment">// 如果 bean为空就返回null</span><br>    <span class="hljs-keyword">if</span> (bean <span class="hljs-keyword">instanceof</span> NullBean) &#123;<br>        <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;<br>    &#125;<br>    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">NamedBeanHolder</span>&lt;T&gt;(beanName, adaptBeanInstance(beanName, bean, requiredType.toClass()));<br>&#125;<br></code></pre></td></tr></table></figure>
<p>最终则来到了 AbstractBeanFactory.java 类的getBean方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> &lt;T&gt; T <span class="hljs-title function_">getBean</span><span class="hljs-params">(String name, <span class="hljs-meta">@Nullable</span> Class&lt;T&gt; requiredType, <span class="hljs-meta">@Nullable</span> Object... args)</span><br>    <span class="hljs-keyword">throws</span> BeansException &#123;<br><br>    <span class="hljs-keyword">return</span> doGetBean(name, requiredType, args, <span class="hljs-literal">false</span>);<br>&#125;<br></code></pre></td></tr></table></figure>
<p>doGetBean 方法的关键内容：（省略了许多 try-catch-finally语句）</p>
</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">protected</span> &lt;T&gt; T <span class="hljs-title function_">doGetBean</span><span class="hljs-params">(</span><br><span class="hljs-params">    String name, <span class="hljs-meta">@Nullable</span> Class&lt;T&gt; requiredType, <span class="hljs-meta">@Nullable</span> Object[] args, <span class="hljs-type">boolean</span> typeCheckOnly)</span><br>    <span class="hljs-keyword">throws</span> BeansException &#123;<br><br>    <span class="hljs-comment">// 转化 Bean 的名称</span><br>    <span class="hljs-type">String</span> <span class="hljs-variable">beanName</span> <span class="hljs-operator">=</span> transformedBeanName(name);<br>    <span class="hljs-comment">// 定义 Bean 的实例</span><br>    Object beanInstance;<br><br>    <span class="hljs-comment">// 从单例缓存中查找 Bean 实例</span><br>    <span class="hljs-type">Object</span> <span class="hljs-variable">sharedInstance</span> <span class="hljs-operator">=</span> getSingleton(beanName);<br>    <span class="hljs-comment">// 如果单例缓存中存在 Bean 实例</span><br>    <span class="hljs-keyword">if</span> (sharedInstance != <span class="hljs-literal">null</span> &amp;&amp; args == <span class="hljs-literal">null</span>) &#123;<br>        <span class="hljs-comment">// ... 打印日志</span><br>        <span class="hljs-comment">// 获取 Bean 的实例对象</span><br>        beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, <span class="hljs-literal">null</span>);<br>    &#125;<br>    <span class="hljs-comment">// 如果单例缓存中不存在 Bean 实例</span><br>    <span class="hljs-keyword">else</span> &#123;<br>        <span class="hljs-comment">// 判断请求的bean是否正在创建</span><br>        <span class="hljs-keyword">if</span> (isPrototypeCurrentlyInCreation(beanName)) &#123;<br>            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">BeanCurrentlyInCreationException</span>(beanName);<br>        &#125;<br>        <span class="hljs-comment">// 检查工厂里是否存在这个Bean</span><br>        <span class="hljs-type">BeanFactory</span> <span class="hljs-variable">parentBeanFactory</span> <span class="hljs-operator">=</span> getParentBeanFactory();<br>        ...<br>        <span class="hljs-keyword">try</span> &#123;<br>           ...<br>            <span class="hljs-type">RootBeanDefinition</span> <span class="hljs-variable">mbd</span> <span class="hljs-operator">=</span> getMergedLocalBeanDefinition(beanName);<br>            <span class="hljs-comment">// 创建 Bean 实例（如果是单例，则直接创建）</span><br>            <span class="hljs-keyword">if</span> (mbd.isSingleton()) &#123;		<span class="hljs-comment">// 单例</span><br>                sharedInstance = getSingleton(beanName, () -&gt; &#123;<br>                   <span class="hljs-keyword">return</span> createBean(beanName, mbd, args);<br>                &#125;);<br>                beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);<br>            &#125;<br><br>            <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (mbd.isPrototype()) &#123;	<span class="hljs-comment">// 多例</span><br>                <span class="hljs-comment">// 创建多例模式的实例</span><br>                <span class="hljs-type">Object</span> <span class="hljs-variable">prototypeInstance</span> <span class="hljs-operator">=</span> <span class="hljs-literal">null</span>;<br>                beforePrototypeCreation(beanName);<br>                prototypeInstance = createBean(beanName, mbd, args);<br>                beanInstance = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);<br>            &#125;<br>            <span class="hljs-keyword">else</span> &#123;<br>                <span class="hljs-type">String</span> <span class="hljs-variable">scopeName</span> <span class="hljs-operator">=</span> mbd.getScope();<br>                <span class="hljs-type">Object</span> <span class="hljs-variable">scopedInstance</span> <span class="hljs-operator">=</span> scope.get(beanName, () -&gt; &#123;<br>                    beforePrototypeCreation(beanName);<br>                    <span class="hljs-keyword">return</span> createBean(beanName, mbd, args);<br>                &#125;);<br>                beanInstance = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);<br>            &#125;<br>        &#125;<br>    &#125;<br>    <span class="hljs-keyword">return</span> adaptBeanInstance(name, beanInstance, requiredType);<br>&#125;<br></code></pre></td></tr></table></figure>
<p><strong>总结：</strong></p>
<ul>
<li>Spring 加载单例的过程是在 BeanFactory的 getBean()方法中被定义的，其默认功能在 AbstractBeanFactory 抽象类里实现，包含的两个主要功能：</li>
</ul>
<ol>
<li>先调用 getSingleton(beanName)从缓存中获取单例Bean </li>
<li>再调用 getObjectForBeanInstance() 从 Bean 的实例中获取对象</li>
</ol>
<p>getBean()方法最终会调用 AbstractBeanFactory 的 doGetBean() 方法，在这个方法中分别处理了 单例对象和原型对象。</p>
<p>getSingleton () 的工作流程：singletonObjects –&gt; earlySingletonObjects –&gt; singletonFactories –&gt; 创建单例实例</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// 单例对象的缓存: 默认大小256</span><br><span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> Map&lt;String, Object&gt; singletonObjects = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ConcurrentHashMap</span>&lt;&gt;(<span class="hljs-number">256</span>);<br><span class="hljs-comment">// 早期单例对象的缓存：bean名称到bean实例, 默认大小16</span><br><span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> Map&lt;String, Object&gt; earlySingletonObjects = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ConcurrentHashMap</span>&lt;&gt;(<span class="hljs-number">16</span>);<br><span class="hljs-comment">// 单例对象的工厂缓存</span><br><span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> Map&lt;String, ObjectFactory&lt;?&gt;&gt; singletonFactories = <span class="hljs-keyword">new</span> <span class="hljs-title class_">HashMap</span>&lt;&gt;(<span class="hljs-number">16</span>);<br><br><br><span class="hljs-comment">// 从缓存中获取单例对象</span><br><span class="hljs-keyword">protected</span> Object <span class="hljs-title function_">getSingleton</span><span class="hljs-params">(String beanName, <span class="hljs-type">boolean</span> allowEarlyReference)</span> &#123;<br>    <span class="hljs-comment">// 通过 Bean的名称查看Bean是否存在</span><br>    <span class="hljs-type">Object</span> <span class="hljs-variable">singletonObject</span> <span class="hljs-operator">=</span> <span class="hljs-built_in">this</span>.singletonObjects.get(beanName);<br>    <span class="hljs-keyword">if</span> (singletonObject == <span class="hljs-literal">null</span> &amp;&amp; isSingletonCurrentlyInCreation(beanName)) &#123;<br>        <span class="hljs-comment">// 查看缓存中是否存在这个 Bean </span><br>        singletonObject = <span class="hljs-built_in">this</span>.earlySingletonObjects.get(beanName);<br>        <span class="hljs-comment">// 若Bean实例为空，则允许懒加载</span><br>        <span class="hljs-keyword">if</span> (singletonObject == <span class="hljs-literal">null</span> &amp;&amp; allowEarlyReference) &#123;<br>            <span class="hljs-comment">// 锁住缓存内的ConcurrentHashMap</span><br>            <span class="hljs-keyword">synchronized</span> (<span class="hljs-built_in">this</span>.singletonObjects) &#123;<br>                <span class="hljs-comment">// 从缓存中获取对象</span><br>                singletonObject = <span class="hljs-built_in">this</span>.singletonObjects.get(beanName);<br>                <span class="hljs-comment">// 若缓存不存在对象</span><br>                <span class="hljs-keyword">if</span> (singletonObject == <span class="hljs-literal">null</span>) &#123;<br>                    <span class="hljs-comment">// 从早期的缓存中查找Bean</span><br>                    singletonObject = <span class="hljs-built_in">this</span>.earlySingletonObjects.get(beanName);<br>                    <span class="hljs-keyword">if</span> (singletonObject == <span class="hljs-literal">null</span>) &#123;<br>                        <span class="hljs-comment">// 最后获取单例工厂</span><br>                        ObjectFactory&lt;?&gt; singletonFactory = <span class="hljs-built_in">this</span>.singletonFactories.get(beanName);<br>                        <span class="hljs-keyword">if</span> (singletonFactory != <span class="hljs-literal">null</span>) &#123;<br>                            <span class="hljs-comment">// 从单例工厂里获取Bean</span><br>                            singletonObject = singletonFactory.getObject();<br>                            <span class="hljs-comment">// 添加早期缓存中</span><br>                            <span class="hljs-built_in">this</span>.earlySingletonObjects.put(beanName, singletonObject);<br>                            <span class="hljs-comment">// 移除当前的缓存</span><br>                            <span class="hljs-built_in">this</span>.singletonFactories.remove(beanName);<br>                        &#125;<br>                    &#125;<br>                &#125;<br>            &#125;<br>        &#125;<br>    &#125;<br>    <span class="hljs-keyword">return</span> singletonObject;<br>&#125;<br></code></pre></td></tr></table></figure>
<p>在上述代码中，<code>synchronized (this.singletonObjects) </code> 的实现支持并发访问，前提部分是isSingletonCurrentlyInCreation方法返回值为 true，即这个 Bean 正在被创建。<br>这里就不继续深入了，主要是了解 Spring源码中用到的单例模式，这里主要是分析了在注入Bean时其单例与多例之间的加载机制，其内部是通过缓存来实现这种单例机制的，而不是直接使用static关键字，其实除了单例模式外，我们在最后的 getSingleton() 方法中也能发现它调用了单例对象工厂的 getObject方法，这里面也实现了工厂模式。</p>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" class="category-chain-item">设计模式</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/">#设计模式</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>设计模式 笔记3 _ 单例模式 在源码中的应用 Runtime 、Integer、Spring @Bean</div>
      <div>http://example.com/2022/07/29/设计模式 笔记3 _ 单例模式 在源码中的应用 Runtime 、Integer、Spring @Bean/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>John Doe</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年7月29日</div>
        </div>
      
      
      <div class="license-meta-item">
        <div>许可协议</div>
        <div>
          
            
            
              <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
              <span class="hint--top hint--rounded" aria-label="BY - 署名">
                <i class="iconfont icon-by"></i>
              </span>
              </a>
            
          
        </div>
      </div>
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/07/29/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%20%E7%AC%94%E8%AE%B011%20_%20%E5%88%9B%E5%BB%BA%E5%9E%8B%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%E5%9C%A8%E6%BA%90%E7%A0%81%E4%B8%AD%E7%9A%84%E5%BA%94%E7%94%A8%20%E6%80%BB%E7%BB%93%E7%AF%87%EF%BC%88%E4%B8%80%EF%BC%89/" title="设计模式 笔记11 _ 创建型设计模式在源码中的应用 总结篇（一）">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">设计模式 笔记11 _ 创建型设计模式在源码中的应用 总结篇（一）</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/07/29/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%20%E7%AC%94%E8%AE%B01%20_%20%E4%BA%94%E4%B8%AA%E5%88%9B%E5%BB%BA%E5%9E%8B%E6%A8%A1%E5%BC%8F%20_%20Java%20%E8%AF%AD%E8%A8%80%E5%AE%9E%E7%8E%B0%20_%20%E5%B7%A5%E5%8E%82%E6%96%B9%E6%B3%95%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%20_%20%E6%8A%BD%E8%B1%A1%E5%B7%A5%E5%8E%82%E6%A8%A1%E5%BC%8F%20_%E5%BB%BA%E9%80%A0%E8%80%85%E6%A8%A1%E5%BC%8F%20_%20%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F%20_%20%E5%8E%9F%E5%9E%8B%E6%A8%A1%E5%BC%8F/" title="设计模式 笔记1 _ 五个创建型模式 _ Java 语言实现 _ 工厂方法设计模式 _ 抽象工厂模式 _建造者模式 _ 单例模式 _ 原型模式">
                        <span class="hidden-mobile">设计模式 笔记1 _ 五个创建型模式 _ Java 语言实现 _ 工厂方法设计模式 _ 抽象工厂模式 _建造者模式 _ 单例模式 _ 原型模式</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      headingSelector : CONFIG.toc.headingSelector || 'h1,h2,h3,h4,h5,h6',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      collapseDepth   : CONFIG.toc.collapseDepth || 0,
      scrollSmooth    : true,
      headingsOffset  : -boardTop
    });
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.10/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
